<?php

namespace app\api\controller;

use addons\shopro\model\Cats;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use addons\shopro\model\Config;
use app\admin\model\AdminLog;
use app\admin\model\CatOrder;
use app\api\controller\Demo;
use app\common\library\Sms as Smslib;
use app\common\model\UserBaofuBank;
use baofu\Baofu;
use think\Controller;
use think\queue\Job;
use think\Loader;
use think\Db;
use addons\shopro\model\User;

/**
 * 订单自动操作
 */
class Task
{
    /**
     * 订单支付
     */
    public function baofuPay()
    {
        $month = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $where = [
            'paytime' => ['<', $month],
            'remaining_cycle' => ['>', 0],
            'unsign' => 0,
            'status' => 4,
        ];

        $lists = CatOrder::where($where)->order('id asc')->select();
        if (!$lists) {
            return false;
        }

        foreach ($lists as $orderInfo) {
            $count = Db::name('baofu_pay')->where('order_id', $orderInfo['id'])
                ->where('status', 2)
                ->where('createtime', '>=', $month)
                ->count();

            if ($count >= 1) {
//                echo date('订单-' . $orderInfo['id'] . ',今日扣款失败超过5次');
//                \think\Log::write('今日订单扣款超过了,订单-' . $orderInfo['id']);
                continue;
            }
            //获取当前客户剩余周期
            Loader::import("\baofu\pay", EXTEND_PATH);
            $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');
            $baofuClass = new \baofu\Pay($config);

            if ($orderInfo['remaining_cycle'] == $orderInfo['total_cycle']) {
                //第一次扣款
                $total_amount = bcmul($orderInfo['remaining_cycle'], $orderInfo['month_money'], 2);
                $txn_amt = bcmul(bcadd($orderInfo['month_money'], bcsub($orderInfo['total_amount'], $total_amount, 2), 2), 100);


                //第一次奖励积分
                $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
                $total_integral = bcmul($integral, $orderInfo['total_cycle'], 2);
                $integral = bcadd($integral, bcsub($orderInfo['score_amount'], $total_integral, 2), 2);
            } else {
                $txn_amt = bcmul($orderInfo['month_money'], 100);
                $integral = bcdiv($orderInfo['score_amount'], $orderInfo['total_cycle'], 2);
            }
            //TODO 走实际支付 $txn_amt
            $baofuData = [
                'user_id' => $orderInfo['user_id'],
                'txn_amt' => $txn_amt,
                'trans_id' => $baofuClass->getTransID(),
                'protocol_no' => $orderInfo['protocol_no'],
                'risk_item' => $orderInfo['RiskItem']
            ];

//                            echo '调用宝付支付'.$txn_amt.'分';
            $result = $baofuClass->singlePay($baofuData);
            $paylog = [
                'user_id' => $orderInfo['user_id'],
                'order_id' => $orderInfo['id'],
                'trans_id' => $baofuData['trans_id'],
                'type' => 'pay',
                'memo' => '订单支付',
                'txn_amt' => bcdiv($txn_amt, 100, 2),
                'cycle' => ($orderInfo['total_cycle'] - $orderInfo['remaining_cycle'] + 1),
                'createtime' => time(),
                'notify' => is_array($result['notify']) ? json_encode($result['notify']) : $result['notify'],
            ];

            $result['code'] = 200;
            if ($result['code'] == 200) {
                $paytime = time();
                CatOrder::where('id', $orderInfo['id'])->setDec('remaining_cycle', 1);

                //检查当前剩余扣款周期
                $info = CatOrder::where('id', $orderInfo['id'])->value('remaining_cycle');
                if ($info == 0) {
                    Db::name('user_baofu_bank')->where('order_id', $orderInfo['id'])->where('status', 2)->update(['status' => 3, 'unbindtime' => time()]);
                }

                CatOrder::where('id', $orderInfo['id'])->update([
                    'paytime' => $paytime,
                    'repayment' => date('d'),
                    'yanqi_day' => '0',
                ]);

                $user = User::get($orderInfo['user_id']);
                $before = $user->money;
                $after = $user->money + $integral;
                $user->money = Db::raw('money + ' . $integral);
                $user->save();
                Db::name('shopro_user_wallet_log')->insert([
                    "user_id" => $orderInfo['user_id'],
                    "wallet" => $integral,       // 符号直接存到记录里面
                    "before" => $before,
                    "after" => $after,
                    "type" => 'cats_recharge',
                    "memo" => '猫咪签约奖励,奖励积分' . $integral,
                    "item_id" => $orderInfo['cat_id'],
                    "wallet_type" => "money",
                    "ext" => '',
                    "oper_type" => 'admin',
                    "oper_id" => 1,
                    'createtime' => time()
                ]);
                Db::name('user_money_log')->insert([
                    'user_id' => $orderInfo['user_id'],
                    'money' => $integral,
                    'before' => $before,
                    'after' => $after,
                    'memo' => '猫咪签约奖励,奖励积分' . $integral,
                    'createtime' => time()
                ]);

                $paylog['status'] = 1;
            } elseif ($result['code'] == 201) {
                //处理中
                CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                //绑定结果查询
                \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryPay', ['baofuData' => $paylog], 'shopro');

                $paylog['status'] = 3;
            } else {
                //订单逾期加一
                CatOrder::where('id', $orderInfo['id'])->setInc('overdue_num', 1);
                CatOrder::where('id', $orderInfo['id'])->where('status', 0)->update(['status' => 6]);

                //$time = time() + 30;
//                \think\Queue::later($time - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');

                //发送失败短信
                $mobile = Db::name('user_baofu_bank')->where('protocol_no', $orderInfo['protocol_no'])->value('phone');
                Smslib::notice($mobile, '', 'sending_2');

                $paylog['status'] = 2;
            }

            Db::name('baofu_pay')->insert($paylog);

        }
    }
}